package com.kehutong.charge.util;

import com.kehutong.charge.entity.ChargeBillItems;
import com.kehutong.charge.entity.MeterReading;
import com.kehutong.common.Java8TimeUtils;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.Pool;

import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

public class PdfUtil {

	private static final Logger logger = LoggerFactory.getLogger(PdfUtil.class);

	private SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
	private SimpleDateFormat formatter1 = new SimpleDateFormat("【yyyy】年【MM】月【dd】日");
	private DecimalFormat moneyFormat = new DecimalFormat("####.00");
	private Calendar calendar = Calendar.getInstance();

	/**
	 * @param htmlUrl
	 * @return
	 */
	private static String inputHtml(String htmlUrl) throws IOException {

		StringBuffer result=new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(htmlUrl),"UTF-8"));

		String str = null;
		while((str = br.readLine())!=null){
			result.append(System.lineSeparator() + str);
		}
		br.close();

		return result.toString();
	}

	public byte[] execute(Map<String,Object> mapParam) throws DocumentException, IOException {

		Document document = null;
		PdfWriter writer = null;
		ByteArrayOutputStream buffer = null;

		document = new Document(PageSize.A4);
		buffer = new ByteArrayOutputStream();
		writer = PdfWriter.getInstance(document, buffer);

		//横向
		Rectangle pageSize = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth());
		pageSize.rotate();
		document.setPageSize(pageSize);

		//创建常用字体
		Font fontChinese = PdfTableUtil.setFonts(10,Color.BLACK);

		//打开Document
		document.open();
		addBody(document, fontChinese,mapParam);

		logger.info("===============PDF文件生成成功！==========================");

		//关闭打开的Document
		document.close();
		writer.flush();
		writer.close();

		return buffer.toByteArray();
	}

	/**
	 * @param document 文档
	 * @param fontChinese 字体
	 * @param mapParam 动态内容
	 * @throws DocumentException
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	private static void addBody(Document document, Font fontChinese,Map<String,Object> mapParam)
			throws DocumentException, MalformedURLException, IOException {

		//添加内容
		Paragraph paragraph = new Paragraph(mapParam.get("company").toString(), PdfTableUtil.setFonts(16, Color.BLACK));
		paragraph.setAlignment(Element.ALIGN_CENTER);
		document.add(paragraph);

		//PdfTableUtil.setParameters(document, "开发者测试", "测试", "测试 开发者 调试", "客户通", "客户通");

		paragraph = new Paragraph(mapParam.get("community").toString(), PdfTableUtil.setFonts(14, Color.BLACK));
		paragraph.setAlignment(Element.ALIGN_CENTER);
		document.add(paragraph);

		paragraph = new Paragraph(mapParam.get("receiptNO").toString(),PdfTableUtil.setFonts(14, Color.RED));
		paragraph.setAlignment(Element.ALIGN_RIGHT);
		document.add(paragraph);

		//姓名 + 楼栋 +房号 ，显示： 张三 12栋-1801
		String showHouse = PdfTableUtil.resultStr(mapParam.get("realName"))+" "+mapParam.get("houseInfo").toString();
		paragraph = new Paragraph(showHouse, PdfTableUtil.setFonts(12,Color.BLACK));
		paragraph.setAlignment(Element.ALIGN_LEFT);
		document.add(paragraph);

		if(mapParam.get("type").equals("receipt")){
			paragraph = new Paragraph("缴费日期："+mapParam.get("datePay"), fontChinese);
		}else{
			paragraph = new Paragraph("打印日期："+mapParam.get("datePay"), fontChinese);
		}
		paragraph.setAlignment(Element.ALIGN_RIGHT);
		document.add(paragraph);

		//添加表格
		document.add(PdfTableUtil.createTable3(mapParam,fontChinese));

		//type : 收据：receipt,缴费单：payBill
		if(mapParam.get("type").equals("receipt")){

			paragraph = new Paragraph("缴费方式: "+mapParam.get("payMethod"), fontChinese);
			paragraph.setAlignment(Element.ALIGN_LEFT);
			//设置左右缩进
			paragraph.setIndentationRight(150.f);
			document.add(paragraph);

			//署名及日期
			paragraph = new Paragraph("企业盖章有效", fontChinese);
			paragraph.setAlignment(Element.ALIGN_RIGHT);
			paragraph.setIndentationRight(100.f);
			document.add(paragraph);
		}

		//盖章
		Image zxdSealImg = Image.getInstance(mapParam.get("sealFile").toString());
		zxdSealImg.scaleToFit(100, 100);
		zxdSealImg.setAlignment(Image.RIGHT);
		//设置签章位置 (高，宽)
		zxdSealImg.setAbsolutePosition(660, 80);
		document.add(zxdSealImg);
	}

	/**
	 * 预览 pdf内容 设置
	 * @param: type : 收据：receipt,缴费单：payBill
	 */
	public Map<String,Object> dataGenera(String fileImg,String company,String type,String msg){

		Map<String,Object> mapParam = new LinkedHashMap<String,Object>();
		mapParam.put("company", company);
		mapParam.put("community","演示小区");
		mapParam.put("realName","张三");  //房东姓名
		mapParam.put("houseInfo","1单元-1010");  //房号
		mapParam.put("datePay", Java8TimeUtils.dateShort());
		mapParam.put("receiptNO","NO: 202108098899");
		mapParam.put("sealFile",fileImg);
		mapParam.put("totalAmount","620.00");
		mapParam.put("content","2021-08-01至2021-08-30");
		mapParam.put("type",type);
		mapParam.put("remark",msg);
		mapParam.put("payMethod","微信支付");

		List<ChargeBillItems> receiptList = new ArrayList<>();
		ChargeBillItems meterReading = Pool.newInstance(ChargeBillItems.class);
		meterReading.setMeterTypeName("水费项(模板数据)");
		meterReading.setLastTimeNumber(new BigDecimal("150.80"));
		meterReading.setTimeNumber(new BigDecimal("190.80"));
		meterReading.setUsageNumber(new BigDecimal("40.00"));
		meterReading.setPrice(new BigDecimal("8.00"));
		meterReading.setPayableAmount(new BigDecimal("320.00"));
		receiptList.add(meterReading);

		meterReading = Pool.newInstance(ChargeBillItems.class);
		meterReading.setMeterTypeName("电费项(模板数据)");
		meterReading.setLastTimeNumber(new BigDecimal("500.00"));
		meterReading.setTimeNumber(new BigDecimal("750.00"));
		meterReading.setUsageNumber(new BigDecimal("150.00"));
		meterReading.setPrice(new BigDecimal("2.00"));
		meterReading.setPayableAmount(new BigDecimal("300.00"));
		receiptList.add(meterReading);

		mapParam.put("dataList",receiptList);

		return mapParam;
	}

}
